'use strict';

/**
 * 通用时间获取
 * @param {Date} time 
 * @param {Number} def 
 * @param {Boolean} offset 
 */
function getTime(time, def = 0, offset = true) {
  let localTime = time.getTime();
  let localOffset = 0;
  if (offset) {
    localOffset = time.getTimezoneOffset() * 60000 + 3600000 * 8; //获得东八区时间偏量
  }
  let utc = localTime + localOffset + (def * 24 * 60 * 60 * 1000);
  return new Date(utc);
}

/**
 * 通用时间字符串获取
 * @param {Date} time 
 * @param {String} moth 
 */
function getStringTime(time, moth = "all") {
  const year = time.getFullYear(); //年
  let date = year + "-";
  const month = time.getMonth() + 1; //月
  if (month < 10) {
    date += "0";
  }
  date += month + "-";
  const day = time.getDate(); //日
  if (day < 10) {
    date += "0";
  }
  date += day;
  if (moth == "day") {
    return date;
  }
  date += " ";
  const hh = time.getHours(); //时
  if (hh < 10) {
    date += "0";
  }
  date += hh + ":";
  const mm = time.getMinutes(); //分
  if (mm < 10) {
    date += "0";
  }
  date += mm + ":";
  const ss = time.getSeconds(); //秒
  if (ss < 10) {
    date += "0";
  }
  date += ss;
  return date;
}

/**
 * 获取当前东八区时间字符串
 */
exports.getGMT8Time = function () {
  let time = getTime(new Date(), 0, true);
  return getStringTime(time);
};

/**
 * 获取时间字符串
 * @param {Date} time 
 */
exports.getStringTime = function (time) {
  if (!time) {
    return null;
  }
  return getStringTime(time);
};

/**
 * 获取日期字符串
 * @param {Date} time 
 */
exports.getStringDay = function (time) {
  if (!time) {
    time = getTime(new Date(), 0, true);
  }
  return getStringTime(time, "day");
};

/**
 * 获取东八区时间戳
 */
exports.getGMT8LongTime = function () {
  return getTime(new Date(), 0, true).getTime();
};

/**
 * 计算2个日期之间相差天数
 * @param {Date} start 
 * @param {Date} end 
 */
exports.getDiffDays = function (start, end) {
  var startLong = start.getTime();
  var endLong = end.getTime();
  var diff = parseInt(Math.abs(startLong - endLong) / 1000 / 60 / 60 / 24);
  return diff;
};
